package cn.mdmbct.douyin.common.session;

import cn.mdmbct.douyin.common.config.DyOpenApiConfig;
import cn.mdmbct.douyin.common.http.HttpExecutor;
import cn.mdmbct.douyin.common.http.HttpExecutorCreator;
import cn.mdmbct.douyin.common.proxy.ServicePath;
import cn.mdmbct.douyin.common.proxy.ServiceRepository;
import lombok.Getter;

/**
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/4/11 15:49
 * @modified mdmbct
 * @since 1.0
 */
public abstract class BaseSession implements DySession {

    protected DyOpenApiConfig openApiConfig;

    @Getter
    protected final ServiceRepository serviceRepository;

    @Getter
    protected final HttpExecutor httpExecutor;


    public BaseSession(DyOpenApiConfig openApiConfig) {
        this.openApiConfig = openApiConfig;
        this.httpExecutor = new HttpExecutorCreator().createHttpExecutor(openApiConfig.getHttp());
        this.serviceRepository = new ServiceRepository(this, httpExecutor);
    }

    @Override
    public void setOpenApiConfig(DyOpenApiConfig config) {
        this.openApiConfig = config;
    }

    @Override
    public DyOpenApiConfig getOpenApiConfig() {
        return openApiConfig;
    }

    protected String accessTokenKey(String openId) {
        return "at_" + openId;
    }

    protected String refreshTokenKey(String openId) {
        return "rt_" + openId;
    }

    protected String clientTokenKey() {
        return "ct_" + openApiConfig.getApp().getKey();
    }

    @Override
    public <T> T getService(Class<T> serviceClass) {
        return serviceRepository.getDyService(serviceClass);
    }

    @Override
    public void addService(ServicePath servicePath) {
        serviceRepository.addServiceInterfaces(servicePath);
    }
}
